import 'dart:async';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:safetymonitor/app/components/toast_widget.dart';
import 'package:safetymonitor/app/core/http/network_manger.dart';
import 'package:safetymonitor/app/core/utils/log_util.dart';

abstract class NetworkUtil {

  static NetworkType _networkType = NetworkType.unknown;

  static StreamSubscription<List<ConnectivityResult>>? _subscription;


  /// 监听网络情况
  static void init() {
    _subscription ??= Connectivity().onConnectivityChanged.listen((List<ConnectivityResult> result) {
      AppLogger.log('网络情况 == $result');
      switch (result.first) {
        case ConnectivityResult.wifi:
          _networkType = NetworkType.wifi;
          NetworkManager.checkNetworkType();
          // AppToast.showSuccess('已连接至WiFi');
          break;
        case ConnectivityResult.mobile:
          _networkType = NetworkType.mobile;
          // AppToast.showError('移动网络连接中');
          break;
        case ConnectivityResult.none:
          _networkType = NetworkType.none;
          AppToast.showError('无网络连接', duration: const Duration(seconds: 3));
          break;
        default:
          _networkType = NetworkType.unknown;
          break;
      }
    });
  }

  static void dispose() {
    _subscription?.cancel();
    _subscription = null;
  }

  static NetworkType get network => _networkType;
}

enum NetworkType {
  wifi,
  mobile,
  none,
  unknown,
}
